//import SignalRService from '@services/signalrService'
import { SIGNALR_HUB_DEVICE_STATUS_URL } from '@/utils/constants'

class DeviceStatusService {
  constructor() {
    this.signalrService = null
    this.isConnected = false
    this.deviceStatusCallbacks = new Set()
  }

  /**
   * 初始化并连接 SignalR
   */
  async connect() {
    if (this.signalrService && this.isConnected) {
      return true
    }

    try {
      this.signalrService = new SignalRService({
        hubUrl: SIGNALR_HUB_DEVICE_STATUS_URL,
        getAccessToken: this.getAccessToken,
        reconnectOptions: {
          maxRetries: 10,
          baseDelayMs: 2000
        },
        log: process.env.NODE_ENV === 'development'
      })

      // 注册消息处理器
      this.signalrService.on('ShowMsg', this.handleDeviceStatusUpdate.bind(this))

      // 连接状态变化处理
      this.signalrService.on('reconnecting', () => {
        console.log('SignalR 重新连接中...')
        this.isConnected = false
      })

      this.signalrService.on('reconnected', () => {
        console.log('SignalR 重新连接成功')
        this.isConnected = true
      })

      await this.signalrService.start()
      this.isConnected = true

      console.log('设备状态服务连接成功')
      return true
    } catch (error) {
      console.error('设备状态服务连接失败:', error)
      this.isConnected = false
      return false
    }
  }

  /**
   * 获取访问令牌
   */
  getAccessToken() {
    // 根据你的认证系统返回 token
    return localStorage.getItem('access_token') || ''
  }

  /**
   * 处理设备状态更新
   */
  handleDeviceStatusUpdate(deviceInfo) {
    console.log('收到设备状态更新:', deviceInfo)

    // 通知所有注册的回调函数
    this.deviceStatusCallbacks.forEach(callback => {
      try {
        callback(deviceInfo)
      } catch (error) {
        console.error('设备状态回调执行失败:', error)
      }
    })
  }

  /**
   * 注册设备状态更新回调
   */
  onDeviceStatusUpdate(callback) {
    if (typeof callback === 'function') {
      this.deviceStatusCallbacks.add(callback)
    }
  }

  /**
   * 取消注册设备状态更新回调
   */
  offDeviceStatusUpdate(callback) {
    this.deviceStatusCallbacks.delete(callback)
  }

  /**
   * 发送消息到服务器（如果需要）
   */
  async sendMessageToServer(methodName, ...args) {
    if (!this.isConnected || !this.signalrService) {
      throw new Error('SignalR 未连接')
    }

    try {
      return await this.signalrService.invoke(methodName, ...args)
    } catch (error) {
      console.error('发送消息失败:', error)
      throw error
    }
  }

  /**
   * 断开连接
   */
  async disconnect() {
    if (this.signalrService) {
      await this.signalrService.stop()
      this.isConnected = false
      this.signalrService = null
    }

    this.deviceStatusCallbacks.clear()
  }

  /**
   * 获取连接状态
   */
  getConnectionStatus() {
    return this.isConnected
  }
}

// 创建单例实例
export default new DeviceStatusService()
